import { defineComponent } from 'vue';
import { getReturnCase } from '@/api/home';
import SheltV2 from '../../common/SheltV2';
import Echarts from '@/components/Echarts';
import { productType } from '../../../Enum';
import './index.less';
import SearchRow from '../SearchRow';
import { dateFormatter } from '@/utils';
import Detail from '../Detail';
import { ActionSheet } from 'vant';
export default defineComponent({
  name: 'Return',
  props: {
    type: {
      type: String,
      default: 'small'
    },
    aspectRatio: {
      type: String,
      default: '2/1'
    }
  },
  setup(props: any) {
    const detailInfo = reactive({
      show: false,
      list: [],
      header: {}
    }) as AnyObject;
    const tableDetail = [
      { title: '产品名称', key: 'configName' },
      { title: '当月退货数', key: 'thisMonthRefundQuantity' },
      { title: '近6个月退货数', key: 'monthRefundQuantity' }
    ];
    const initData = ref({ date: new Date(), type: 0 }) as AnyObject;
    const showOverView = ref(true);
    const detailRef = ref();
    const overviewData = ref({}) as AnyObject;
    const data = reactive({
      search: {
        month: [new Date().getFullYear(), new Date().getMonth() + 1],
        page: 1,
        pageSize: 15,
        type:1
      },
      list: [
        {
          key: 'month',
          type: 'popup',
          title: '日期选择',
          icon: 'calendar',
          placeholder: '请选择'
        },
        {
          key: 'type',
          type: 'list',
          title: '项目类型',
          placeholder: '项目类型',
          list: productType
        }
      ],
      tab: {
        key: '',
        list: [
          { label: '数据展示', value: 0 },
          { label: '详情', value: 1 }
        ]
      }
    }) as AnyObject;
    const option = ref({
      tooltip: {
        trigger: 'item',
        // @ts-ignore
        position: function (point, params, dom, rect, size) {
          // 宽度超出
          console.log(point,size);
          
          const overX = point[0] + size.contentSize[0] > size.viewSize[0];
          const overY = point[1] + size.contentSize[1] > size.viewSize[1];
          if (overX || overY) {            
            return [overX ? 0 : point[0], overY ? 1 : point[1]];
          } else {
            return point;
          }
       
        }
      },
      title: {
        text: '', //主标题文本，'\n'指定换行
        subtext: '本月退货率',
        left: '24%',
        textAlign: 'center',
        y: 'center',
        textStyle: {
          color: '#000',
          fontSize: 24
        },
        subtextStyle: {
          color: '#666666',
          fontSize: '12px'
        },
        itemGap: 0
      },
      color: [
        '#ffb17d',
        '#ffc824',
        '#63d3ff',
        '#40a6ff',
        '#4a74ea',
        '#1ac48b',
        '#fc8844',
        'gray'
      ],
      legend: {
        orient: 'vertical',
        top: 'center',
        right: '0%',
        legend: { left: '10%' },
        icon: 'circle',
        itemWidth: 8,
        textStyle: {
          rich: {
            a: {
              fontSize: 12,
              color: '#666666'
            }
          }
        }
      },
      series: [
        {
          name: '退货情况',
          type: 'pie',
          radius: ['70%', '90%'],
          avoidLabelOverlap: false,
          center: ['25%', '50%'],
          itemStyle: {
            borderRadius: 2
          },
          label: {
            show: false
          },
          labelLine: {
            show: true,
            length: 5
          },
          data: []
        }
      ]
    }) as any;
    const detailSlots = ref({
      fill: () => <SearchRow onSearch={getReturnCaseData} data={data} />
    });

    const viewDetail = () => {
      detailRef.value.show = true;
    };
    const handleTab = (val: number) => {
      showOverView.value = !val;
    };

    getReturnCaseData();
    function getReturnCaseData() {
      const { month, ...resets } = data.search;
      const real_month = dateFormatter(month);
      getReturnCase({ month: real_month, ...resets }).then((res: AnyObject) => {
        overviewData.value = res;
        const _arr = [] as any;
        res.datas.slice(0, 7)?.forEach((_item: AnyObject, _index: number) => {
          _arr[_index] = {
            name: _item.configName,
            value: _item.thisRefundRate
          };
        });

        option.value.series[0].data = _arr;
        option.value.title.text = res.thisRate + '%';
        option.value.legend.formatter = (name: string) => {
          const findItem = _arr?.find(
            (_item: AnyObject) => _item.name === name
          );
          const joinText = findItem
            ? name + '     ' + findItem.value + '%'
            : '';
          const revealName =
            joinText.length > 16 ? joinText.slice(0, 16) + '...' : joinText;
          return `{a|${revealName}}`;
        };
      });
    }
    const search = (val: AnyObject) => {
      const { month, type, ...resets } = val;
      const real_month = dateFormatter(month);
      const real_type = type.value ?? type;
      getReturnCase({ month: real_month, type: real_type, ...resets }).then(
        (res: AnyObject) => {
          overviewData.value = res;
        }
      );
    };
    const viewLiDetail = (item: AnyObject) => {
      console.log(item);
      detailInfo.show = true;
      detailInfo.header = {
        title: item.configName
      };
      detailInfo.list = [
        { name: '当月销售数', content: item.thisMonthQuantity },
        { name: '近6个月销售数', content: item.monthQuantity },
        { name: '当月退货数', content: item.thisMonthRefundQuantity },
        { name: '近6个月退货数', content: item.monthRefundQuantity },
        { name: '当月退货率', content: item.thisRefundRate + '%' },
        { name: '近6个月退货率', content: item.monthRefundRate + '%' }
      ];
    };

    return () => (
      <>
        <SheltV2
          title="退货情况"
          question="<div><p>【该数据每日02:00更新一次】</p><p>退货情况数据来源于BI，统计直营电商亚马逊的退货数据。</p></div>"
          more="查看全部"
          v-slots={detailSlots.value}
          onViewDetail={viewDetail}
        >
          <Echarts aspectRatio={props.aspectRatio} option={option.value} />
          {Boolean(initData.value.total) && (
            <p class="fill_legend flex-start">
              <div class="circle"></div>
              <span>其他</span>
              <span>...</span>
            </p>
          )}
        </SheltV2>
        <Detail
          onHandleTab={handleTab}
          onSearch={search}
          title="历史退货情况"
          ref={detailRef}
          filterDetail={data}
          tableDetail={tableDetail}
          requestApi={getReturnCase}
          onViewLiDetail={viewLiDetail}
        >
          {showOverView.value && (
            <div class="data_overview">
              <div class="overvire_item">
                <p class="num">{overviewData.value?.thisCount}</p>
                <p>当月销售数</p>
              </div>
              <div class="overvire_item">
                <p class="num">{overviewData.value?.thisRefundCount}</p>
                <p>当月退货数</p>
              </div>
              <div class="overvire_item">
                <p class="num">{overviewData.value?.thisRate + '%'}</p>
                <p>当月退货率</p>
              </div>
              <div class="overvire_item">
                <p class="num">{overviewData.value?.monthCount}</p>
                <p>近6个月销售数</p>
              </div>
              <div class="overvire_item">
                <p class="num">{overviewData.value?.monthRefundCount}</p>
                <p>近6个月退货数</p>
              </div>
              <div class="overvire_item">
                <p class="num">{overviewData.value?.monthRate + '%'}</p>
                <p>近6个月退货率</p>
              </div>
            </div>
          )}
        </Detail>
        <ActionSheet
          v-model:show={detailInfo.show}
          title="退货详情"
          class="detailinfo"
        >
          <div class="detailinfo_header">
            <div class="title">{detailInfo.header.title}</div>
          </div>
          <ul class="detailinfo_content">
            {detailInfo.list.map((item: AnyObject) => (
              <li class="flex-start">
                <div class="title">{item.name}</div>
                <div class="content">{item.content}</div>
              </li>
            ))}
          </ul>
        </ActionSheet>
      </>
    );
  }
});
